package com.mikeorth.view
{
	import com.mikeorth.controls.HandCursorButton;
	
	import flash.events.MouseEvent;
	
	import mx.containers.ControlBar;
	import mx.containers.TitleWindow;
	import mx.core.EdgeMetrics;
	import mx.core.UIComponent;
	import mx.events.CloseEvent;
	import mx.events.FlexEvent;
	import mx.events.ResizeEvent;
	import mx.managers.PopUpManager;

	public class PopupWithControlBar extends TitleWindow
	{
		// TODO: create style properties for buttons
		public var saveButton:HandCursorButton;
		public var cancelButton:HandCursorButton;

		public var keepCentered:Boolean = false;
		
		private var sizeChanged:Boolean = false;
		private var labelChanged:Boolean = false;
		private var showCancelButtonChanged:Boolean = false;
		private var showSaveButtonChanged:Boolean = false;
		
		//-----------------------
		// saveLabel
		//-----------------------
		private var _saveLabel:String = "Save";
		public function get saveLabel ():String {
			return _saveLabel;
		}
		public function set saveLabel (value:String):void {
			_saveLabel = value;
			labelChanged = true;
			invalidateProperties();
		}

		//----------------------
		// showSaveButton
		//----------------------
		private var _showSaveButton:Boolean = true;
		public function get showSaveButton ():Boolean {
			return _showSaveButton;
		}
		public function set showSaveButton (value:Boolean):void {
			_showSaveButton = value;
			showSaveButtonChanged = true;
			invalidateProperties();
		}

		//-----------------------
		// cancelLabel
		//-----------------------
		private var _cancelLabel:String = "Cancel";
		public function get cancelLabel ():String {
			return _cancelLabel;
		}
		public function set cancelLabel (value:String):void {
			_cancelLabel = value;
			labelChanged = true;
			invalidateProperties();
		}
		//----------------------
		// showCancelButton
		//----------------------
		private var _showCancelButton:Boolean = true;
		public function get showCancelButton ():Boolean {
			return _showCancelButton;
		}
		public function set showCancelButton (value:Boolean):void {
			_showCancelButton = value;
			showCancelButtonChanged = true;
			invalidateProperties();
		}


	
		
		public function PopupWithControlBar()
		{
			super();
			showCloseButton = true;
			//styleName = "Popup";
			// setup hooks for closing window
			this.addEventListener(CloseEvent.CLOSE, onClose);
			addEventListener(ResizeEvent.RESIZE, onResize);
			
			
		}
		
		
		/*=============== LISTENERS =========================*/
		private function onSaveClick(event:MouseEvent):void {
			save();
		}
		private function onCancelClick(event:MouseEvent):void {
			cancel();
		}
		private function onInitialize(event:FlexEvent):void {
			removeEventListener(FlexEvent.INITIALIZE, init);
			init();
		}
		
		/**
		 * Keeps a popup centered when resizing. 
		 * @param event
		 * 
		 */		
		private function onResize(event:ResizeEvent):void
		{
			if (keepCentered)
			{
				x = stage.width/2 - width/2;
				y = stage.height/2 - height/2;
			}
		}
		
		
		protected function onClose(event:CloseEvent):void
		{
			// set model variable to null so that reference is lost for GC to do its stuff
			PopUpManager.removePopUp(this);
			// TODO: remove listeners
			
		}
		
		/**
		 * Centers the container on a <code>ResizeEvent</code> if needed.
		 * @param event ResizeEvent
		 * 
		 */		
	/*================= PROTECTED METHODS ===================*/
		/**
		 * Override these in subclass. 
		 */		
		protected function save():void {}
		protected function cancel():void {
			dispatchEvent(new CloseEvent(CloseEvent.CLOSE));
		}
		
		protected function init():void {}
	
	
	
	/*================= PUBLIC FUNCTIONS ===================*/
		public function addChildToControlBar(uic:UIComponent, index:int=0):void {
			ControlBar(this.controlBar).addChildAt(uic, index);
		}
		
	/*================= OVERRIDES ===================*/
		override protected function createChildren():void {
			super.createChildren();
			
			if (!saveButton && showSaveButton) {
				saveButton = new HandCursorButton();
				saveButton.label = saveLabel;
				// TODO: add icon
				saveButton.addEventListener(MouseEvent.CLICK, onSaveClick);
				// TODO: Make style settable
				saveButton.styleName = "orangeButton"
				
			}
			if (!cancelButton && showCancelButton) {
				cancelButton = new HandCursorButton()
				cancelButton.label = cancelLabel;
				// TODO: add icon
				cancelButton.addEventListener(MouseEvent.CLICK, onCancelClick);
				cancelButton.styleName = "greyButton";
			}
			if (!controlBar) {
				/*  The listener for init must be added here because calling createComponentsFromDescriptors
					dispatches a second initialize event!
				*/
				addEventListener(FlexEvent.INITIALIZE, onInitialize, false, 0, true);
				this.controlBar = new ControlBar();
				this.addChildAt(ControlBar(this.controlBar),this.numChildren);
                this.createComponentsFromDescriptors();
				if (saveButton) ControlBar(this.controlBar).addChild(saveButton);
				if (cancelButton) ControlBar(this.controlBar).addChild(cancelButton);
				ControlBar(this.controlBar).setStyle("horizontalAlign", "right");
			}
			
			// give it a good border
			setStyle("borderAlpha", 1);
		}

		override protected function commitProperties():void {
			super.commitProperties();
			
			if (labelChanged) {
				labelChanged = false;
				if (saveButton) saveButton.label = saveLabel;
				if (cancelButton) cancelButton.label = cancelLabel;
			}
		}
		
		override protected function layoutChrome(unscaledWidth:Number, unscaledHeight:Number):void {
			super.layoutChrome(unscaledWidth, unscaledHeight);
			//titleBar.setActualSize(titleBar.width - 5, titleBar.height - 5);
			titleBar.move(0,10);
		}
		
		override public function get viewMetrics():EdgeMetrics {
		    // has to be cloned!
		    var metrics : EdgeMetrics = super.viewMetrics.clone();

		    if (controlBar) 
		        metrics.bottom = controlBar.height
		    
		    return metrics;
		}
	}
}